package com.xiaoyu.lingdian.tool.wx;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import com.xiaoyu.lingdian.entity.weixin.Constant;
import com.xiaoyu.lingdian.tool.DateUtil;
import com.xiaoyu.lingdian.tool.IOUtil;

/**
 * 获取configToken
 */
public class GetExistConfigToken {

	// 获取jsapi_ticket的接口地址（GET） 缓存7200秒  
	public static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		
    //定义一个私有的静态全局变量来保存该类的唯一实例
    private static GetExistConfigToken getExistConfigToken;

    private GetExistConfigToken() {}

    public static GetExistConfigToken getInstance() {
        //单例模式
        if ( getExistConfigToken == null) {
        	getExistConfigToken = new GetExistConfigToken();
        }
        return getExistConfigToken;
    }

   public String getExistConfigToken(String appid, String at, String fileName) {
	   Map<String, String> map = new HashMap<String, String>();
       // 读取文件中的configToken数据
       String filepath = GetExistConfigToken.class.getResource("").getPath() + "config/" + fileName + ".txt";       
       System.out.println("existConfigTokenfilepath:" + filepath);
       if(filepath.startsWith("/"))
    	   filepath = filepath.substring(1, filepath.length());
       try {          
    	   map = IOUtil.readToMap(filepath);
    	   String lastTime = map.get("lastTime");
    	   String configToken = map.get("configToken");
           Date now = new Date();
           Date configExpires = DateUtil.parseDate(lastTime, "yyyy-MM-dd HH:mm:ss");
           if (now.getTime() > configExpires.getTime()) {
        	   configToken = getConfigToken(appid, at);
        	   configExpires = new Date(now.getTime() + 7000000); //默认7200000秒
               String nextTime = DateUtil.formatDate("yyyy-MM-dd HH:mm:ss", configExpires);
               String content = "configToken="+configToken+"\r\nlastTime="+nextTime;
               IOUtil.write(filepath, content);
           }
           return configToken;
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       return "";
   }

	/**
	 * 获取ticket
	 * 
	 * @param appid 微信appid
	 * @param at 微信access_token
	 * @return
	 */
	public static String getConfigToken(String appid, String at) {
		String ticket = "";
		if (("").equals(appid)) {
			appid = Constant.APP_ID;
		}
		
		String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", at);
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
            try {
                ticket = jsonObject.getString("ticket");
                return ticket;
            } catch (JSONException e) {
            	return "";
            }
        }
		
		return ticket;
	}
	
}